import React, { useState, useEffect, useRef } from 'react';
import SignatureCanvas from 'react-signature-canvas';
import { Modal, Spin, message } from 'antd';
import { userPersonSignImg } from '@/services/user';
import styles from './index.less';

interface SignatureProps {
  getSigin: (imgStr: string) => any;
  getCanvasRef?: (ref: React.MutableRefObject<null>) => void;
  back: () => void;
  modalVisible: boolean;
}
const Signature: React.FC<SignatureProps> = (props) => {
  const { getSigin, getCanvasRef, back, modalVisible } = props;
  const signCanvas = useRef();
  const [minHeight, setMinHeight] = useState<number>(600);
  const [signData, setSignData] = useState<any>();
  const [showSign, setShowSign] = useState<boolean>(false);

  const rotateBase64Img = (src: any, edg: number, callback: (imgData: any) => void) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    let edg_d = edg;
    if (edg_d < 0) {
      edg_d = (edg_d % 360) + 360
    }

    let imgW; //图片宽度
    let imgH; //图片高度
    let size; //canvas初始大小

    if (edg_d % 90 != 0) {
      console.error('旋转角度必须是90的倍数!');
      throw '旋转角度必须是90的倍数!';
    }
    
    const quadrant = (edg_d / 90) % 4; //旋转象限
    const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; //裁剪坐标

    const image = new Image();
    image.crossOrigin = 'anonymous';
    image.src = src;

    image.onload = function () {
      imgW = image.width;
      imgH = image.height;
      size = imgW > imgH ? imgW : imgH;

      canvas.width = size * 2;
      canvas.height = size * 2;
      switch (quadrant) {
        case 0:
          cutCoor.sx = size;
          cutCoor.sy = size;
          cutCoor.ex = size + imgW;
          cutCoor.ey = size + imgH;
          break;
        case 1:
          cutCoor.sx = size - imgH;
          cutCoor.sy = size;
          cutCoor.ex = size;
          cutCoor.ey = size + imgW;
          break;
        case 2:
          cutCoor.sx = size - imgW;
          cutCoor.sy = size - imgH;
          cutCoor.ex = size;
          cutCoor.ey = size;
          break;
        case 3:
          cutCoor.sx = size;
          cutCoor.sy = size - imgW;
          cutCoor.ex = size + imgH;
          cutCoor.ey = size + imgW;
          break;
      }

      ctx.translate(size, size);
      ctx.rotate((edg_d * Math.PI) / 180);
      ctx.drawImage(image, 0, 0);

      const imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
      if (quadrant % 2 == 0) {
        canvas.width = imgW;
        canvas.height = imgH;
      } else {
        canvas.width = imgH;
        canvas.height = imgW;
      }
      ctx.putImageData(imgData, 0, 0);
      callback(canvas.toDataURL('image/png'));
    };
  };

  const detectOrient = function (id = 'content') {
    const width = document.documentElement.clientWidth;
    const height = document.documentElement.clientHeight;
    const $wrapper = document.getElementById(id);
    // const parentElement = document.getElementById('signContent');
    // const canvasElement = signCanvas?.current.getCanvas();

    if (width < height) {
      setMinHeight(600);
      let style = '';
      let canvasStyle = '';
      const styleH = height > 580 ? 580 : height;
      const styleW = width - 30;
      style += '-webkit-transform: rotate(90deg); transform: rotate(90deg);';
      style += '-webkit-transform-origin: ' + styleW / 2 + 'px ' + styleW / 2 + 'px;';
      style += 'transform-origin: ' + styleW / 2 + 'px ' + styleW / 2 + 'px;';
      // style += 'width:' + styleW + 'px;';
      // style += 'height:' + styleW + 'px;';
      $wrapper!.style.cssText = style;

      const signDiv = document.getElementById('signDiv');
      signDiv!.style.cssText = 'height: ' + styleW + 'px;width:' + styleH + 'px;';
      //将签名还原翻转，就可以保证在横屏情况下保证画笔的方向跟手势一致，然后再进行高度和宽度的调整。
      const parentElement = document.getElementById('signContent');
      const pw = parentElement!.clientWidth; //容器宽
      const ph = parentElement!.clientHeight - 10; //容器高
      const pch = styleW - 78;
      //因为会旋转，canvas 宽 高 分别对应容器的 高 宽
      parentElement!.style.cssText = 'height: ' + pch + 'px;width:' + styleH + 'px;';

      const canvasElement = signCanvas?.current.getCanvas();
      canvasElement.height = pw;
      canvasElement.width = pch;
      canvasStyle +=
        'transform-origin: ' + pch / 2 + 'px ' + pch / 2 + 'px;transform: rotate(-90deg);';
      canvasStyle += 'background: #e5e5e5;' + `height:${pw}px;width:${pch}px;`;
      canvasElement.style.cssText = canvasStyle;
    } else {
      setMinHeight(420);
      let style = '';
      let canvasStyle = '';
      const parentElement = document.getElementById('signContent');
      const pw = parentElement!.clientWidth;
      let ph = parentElement!.clientHeight;
      ph = ph > 0 ? ph : 310;

      style += 'width:' + pw + 'px;';
      style += 'height:' + ph + 'px;';
      $wrapper!.style.cssText = style;
      
      parentElement!.style.cssText = 'height: ' + ph + 'px';

      const canvasElement = signCanvas?.current.getCanvas();
      canvasElement.height = ph;
      canvasElement.width = pw;
      canvasStyle += 'background: #e5e5e5;' + `height:${ph}px;width:${pw}px;`;
      canvasElement.style.cssText = canvasStyle;
    }
  };

  const getSiginImg = async () => {
    const res = await userPersonSignImg();
    if (res && res.success) {
      setSignData(res.data);
    }
  };

  useEffect(() => {
    detectOrient();
    getSiginImg();
  }, []);

  const confirmSign = () => {
    if (signCanvas!.current.isEmpty() && !showSign) {
      message.info('请先签字');
      return;
    }
    if (showSign) {
      getSigin(signData.base64);
    } else {
      const sign = signCanvas!.current.toDataURL('image/png');
      //在横屏时需要旋转图片
      if (minHeight == 600) {
        rotateBase64Img(sign, 270, (img) => {
          getSigin(img);
        })
      } else {
        getSigin(sign);
      }
    }
  };

  return (
    <Modal
      destroyOnClose
      visible={modalVisible}
      width={800}
      bodyStyle={{ minHeight: `${minHeight}px` }}
      footer={null}
      closable={false}
      centered={true}
    >
      <div className={styles.sign} id="content">
        <div className={styles.signContainer} id="signDiv">
          <div className={styles.salarySignContainer}>
            <div className={styles.salarySignTitle}>
              <div
                className={styles.goBack}
                onClick={() => {
                  back();
                }}
              >
                关闭
              </div>
              请签名确认
            </div>
            {/* 画布 */}
            <div id="signContent" className={styles.salarySignContent}>
              <SignatureCanvas ref={signCanvas} penColor="#000" />
              {showSign && signData && (
                <img
                  id="signImg"
                  src={'data:image/png;base64,' + signData.base64}
                  className={styles.signImg}
                />
              )}
            </div>
            {/* 按钮 */}
            <div
              className={styles.salarySignBar}
              style={{
                gridTemplateColumns: signData && signData.base64 ? '1fr 1fr 1fr' : '1fr 1fr',
              }}
            >
              {signData && signData.base64 && (
                <div
                  className={styles.salarySignBtn}
                  onClick={() => {
                    setShowSign(true);
                  }}
                >
                  已有签名
                </div>
              )}
              <div
                className={styles.salarySignBtn}
                onClick={() => {
                  signCanvas.current?.clear();
                  setShowSign(false);
                }}
              >
                重写
              </div>
              <div
                className={styles.salarySignBtn}
                onClick={() => {
                  confirmSign();
                }}
              >
                确认
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
export default Signature;
